package com.five.years.common;

import com.five.years.common.exception.BusinessException;
import com.five.years.common.utils.DateUtils;
import com.five.years.common.utils.EnvUtils;
import com.five.years.common.utils.RedisUtils;
import com.five.years.common.utils.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.beans.PropertyEditorSupport;
import java.util.Date;
import java.util.List;

/**
 * @author : qinhuajun
 * @Date :2020-03-06
 */
public class BaseApiController {

    public static String TEMP_PATH = "";

    @InitBinder
    protected void init(WebDataBinder binder) {
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(dataBinder(text));
            }
        });
    }

    protected Date dataBinder(String value) {
        //常规的日期格式
        if (StringUtils.isNotEmpty(value)) {
            Date parseDate;
            if (value.contains("/") || value.contains(".") || value.contains("-")) {
                parseDate = DateUtils.parseDate(value);
            } else {
                parseDate = new Date(Long.valueOf(value));
            }
            return parseDate;
        }
        return null;
    }

    /**
     * 接口入参参数验证
     */
    protected void paramsValid(BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            List<ObjectError> errors = bindingResult.getAllErrors();
            if (errors != null && !errors.isEmpty()) {
                ObjectError error = errors.get(0);
                throw new BusinessException(SystemCode.PARAM_ERROR.getCode(), error.getDefaultMessage());
            }
        }
    }

    /**
     * 检测刷新token
     */
    public static boolean checkAndRefreshToken() {
        if (Constants.DEPLOY_ENV.LOCAL.equals(EnvUtils.deplayEnv())) {
            return true;
        }
        String token = getToken();
        if (StringUtils.isBlank(token)) {
            return false;
        }
        if (RedisUtils.REDIS_TOKEN.exists(token)) {
            RedisUtils.REDIS_TOKEN.expire(token, Constants.TTL.MONTH);
            return true;
        }
        if (Constants.TRUE.equals(RedisUtils.REDIS_TOKEN.hGet(Constants.RedisKey.LOGIN_EXTRUDE, token))) {
            RedisUtils.REDIS_TOKEN.hDel(Constants.RedisKey.LOGIN_EXTRUDE, token);
            throw new BusinessException(SystemCode.TOKEN_INVALID);
        }
        throw new BusinessException(SystemCode.TOKEN_EXPIRE);
    }


    /**
     * 获取token
     */
    protected static String getToken() {
        if (RequestContextHolder.getRequestAttributes() == null) {
            return null;
        }
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request == null) {
            return null;
        }
        String token = request.getHeader(Constants.HTTP_HEADER_ACCESS_TOKEN);
        if (StringUtils.isNull(token)) {
            return null;
        }
        return token;
    }

    public static void removeToken() {
        String token = getToken();
        if (!StringUtils.isEmpty(token)) {
            RedisUtils.REDIS_TOKEN.del(token);
        }
    }
}
